package com.hugh.commom.util;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: Hugh
 * @Date: 2020/6/21
 */
public class NetworkUtils {
    /**
     * 获取当前机器端口号
     *
     */
    public static String getLocalPort() throws Exception {
        MBeanServer server;
        if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
            server = MBeanServerFactory.findMBeanServer(null).get(0);
        } else {
            return "";
        }
        Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
                Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));

        Iterator<ObjectName> iterator = names.iterator();
        if (iterator.hasNext()) {
            ObjectName name = iterator.next();
            return server.getAttribute(name, "port").toString();
        }
        return "";
    }

    /**
     * 获取当前机器的IP
     *
     */
    public static String getLocalIP() throws Exception {
        InetAddress addr = InetAddress.getLocalHost();
        byte[] ipAddr = addr.getAddress();
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
        return ipAddrStr;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getLocalPort());
    }
}
